<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" label-width="90px">
      <el-row :gutter="10">
        <!-- 默认显示的查询字段 -->
        <el-col :span="6">
          <el-form-item label="it设备编码" prop="deviceCode">
            <el-input
              v-model="queryParams.deviceCode"
              placeholder="请输入it设备编码"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="责任人姓名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入责任人姓名"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="IP地址" prop="ipAddress">
            <el-input
              v-model="queryParams.ipAddress"
              placeholder="请输入IP地址"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

      
        <!-- 高级搜索字段（默认隐藏） -->
        <template v-if="showAdvancedSearch">
        <el-col :span="6">
          <el-form-item label="责任人编号" prop="userId">
            <el-input
              v-model="queryParams.userId"
              placeholder="请输入责任人编号"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备类型" prop="typeId">
            <el-input
              v-model="queryParams.typeId"
              placeholder="请输入设备类型"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="地理位置" prop="dictName">
            <el-input
              v-model="queryParams.dictName"
              placeholder="请输入地理位置名称"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备用途" prop="purposeId">
              <Treeselect
                v-model="queryParams.purposeId"
                placeholder="请选择设备用途"
                :options="devicePurposeData"
                :normalizer="node => ({ id: node.dictValue, label: node.dictName, children: node.children })"
                :show-count="true"
                noChildrenText=""
              />
            </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属部门" prop="deptName">
            <el-input
              v-model="queryParams.deptName"
              placeholder="请输入所属部门"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="品牌" prop="brandId">
            <el-select v-model="queryParams.brandId" placeholder="请选择品牌" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.device_brand"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="型号" prop="model">
            <el-input
              v-model="queryParams.model"
              placeholder="请输入型号"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="来源" prop="sourceId">
            <el-select v-model="queryParams.sourceId" placeholder="请选择来源" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.device_source"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="密级" prop="securityId">
            <el-select v-model="queryParams.securityId" placeholder="请选择密级" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.secret_level"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="网络类型" prop="networkId">
            <el-select v-model="queryParams.networkId" placeholder="请选择网络类型" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.network_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式" prop="contact">
            <el-input
              v-model="queryParams.contact"
              placeholder="请输入联系方式"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="操作系统安装日期">
            <el-date-picker
              v-model="daterangeOsInstallDate"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="操作系统类型" prop="osId">
            <el-select v-model="queryParams.osId" placeholder="请选择操作系统类型" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.os_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备序列号" prop="deviceSerial">
            <el-input
              v-model="queryParams.deviceSerial"
              placeholder="请输入设备序列号"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="CPU核心数" prop="numberOfCpu">
            <el-input
              v-model="queryParams.numberOfCpu"
              placeholder="请输入CPU核心数"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="内存容量" prop="memoryCapacity">
            <el-input
              v-model="queryParams.memoryCapacity"
              placeholder="请输入内存容量"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="水印编码" prop="watermarkCode">
            <el-input
              v-model="queryParams.watermarkCode"
              placeholder="请输入水印编码"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="启用日期">
            <el-date-picker
              v-model="daterangeActivationDate"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电子钥匙编号" prop="keyCode">
            <el-input
              v-model="queryParams.keyCode"
              placeholder="请输入电子钥匙编号"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="使用情况" prop="usageId">
            <el-select v-model="queryParams.usageId" placeholder="请选择使用情况" clearable style="width: 100%">
              <el-option
                v-for="dict in dict.type.usage_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="硬盘序列号" prop="hddSerial">
            <el-input
              v-model="queryParams.hddSerial"
              placeholder="请输入硬盘序列号"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="MAC地址" prop="macAddress">
            <el-input
              v-model="queryParams.macAddress"
              placeholder="请输入MAC地址"
              clearable
              @keyup.enter.native="handleQuery"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        
        <!-- 高级搜索状态下的按钮组 - 将间距缩短一半 -->
        <el-col :span="3">
          <el-form-item label="" label-width="40px">
            <div style="display: flex; gap: 5px;">
              <el-button
                type="primary"
                plain
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
              >搜索</el-button>
              <el-button
                plain
                icon="el-icon-refresh"
                size="mini"
                @click="resetQuery"
              >重置</el-button>
              <el-button
                type="info"
                plain
                size="mini"
                @click="toggleAdvancedSearch"
              >{{ advancedSearchText }}</el-button>
            </div>
          </el-form-item>
        </el-col>
        </template>
        
        <!-- 默认状态下的按钮组 - 将间距缩短一半 -->
        <template v-if="!showAdvancedSearch">
          <el-col :span="3">
            <el-form-item label="" label-width="40px">
              <div style="display: flex; gap: 5px;">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQuery"
                >搜索</el-button>
                <el-button
                  plain
                  icon="el-icon-refresh"
                  size="mini"
                  @click="resetQuery"
                >重置</el-button>
                <el-button
                  type="info"
                  plain
                  size="mini"
                  @click="toggleAdvancedSearch"
                >{{ advancedSearchText }}</el-button>
              </div>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:deviceManage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['manage:deviceManage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:deviceManage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:deviceManage:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="deviceManageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="it设备编码" align="center" prop="deviceCode" />
      <el-table-column label="设备类型" align="center" prop="typeName" />        
      <el-table-column label="地理位置" align="center" prop="dictName" />   
      <el-table-column label="所属部门" align="center" prop="deptId">
        <template slot-scope="scope">
          <span>{{ getDeptNameById(scope.row.deptId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="责任人" align="center" prop="userName" />
      <el-table-column label="密级" align="center" prop="securityId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.secret_level" :value="scope.row.securityId"/>
        </template>
      </el-table-column>
      <el-table-column label="网络类型" align="center" prop="networkId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.network_type" :value="scope.row.networkId"/>
        </template>
      </el-table-column>
      <el-table-column label="启用日期" align="center" prop="activationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用情况" align="center" prop="usageId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.usage_status" :value="scope.row.usageId"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click.stop="handleUpdate(scope.row)"
            v-hasPermi="['manage:deviceManage:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleNewDetail(scope.row)"
            v-hasPermi="['manage:deviceManage:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:deviceManage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="it设备编码" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入it设备编码" readonly style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备类型" prop="typeId">
              <Treeselect
                v-model="form.typeId"
                :options="deviceTypeData"
                :normalizer="node => ({ id: node.dictValue, label: node.dictName, children: node.children })"
                placeholder="请选择设备类型"
                clearable
                searchable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地理位置" prop="locationId">
              <Treeselect
                v-model="form.locationId"
                :options="treeDictData"
                :normalizer="node => ({ id: node.dictValue, label: node.dictName, children: node.children })"
                placeholder="请选择地理位置"
                clearable
                searchable
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="品牌" prop="brandId">
              <el-select v-model="form.brandId" placeholder="请选择品牌" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.device_brand"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="来源" prop="sourceId">
              <el-select v-model="form.sourceId" placeholder="请选择来源" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.device_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="密级" prop="securityId">
              <el-select v-model="form.securityId" placeholder="请选择密级" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.secret_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备用途" prop="purposeId">
              <Treeselect
                v-model="form.purposeId"
                placeholder="请选择设备用途"
                :options="devicePurposeData"
                :normalizer="node => ({ id: node.dictValue, label: node.dictName, children: node.children })"
                :show-count="true"
                noChildrenText=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网络类型" prop="networkId">
              <el-select v-model="form.networkId" placeholder="请选择网络类型" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.network_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="资产所属部门" prop="deptId">
              <Treeselect
                v-model="form.deptId"
                placeholder="请选择资产所属部门"
                :options="deptTreeData"
                :normalizer="normalizer"
                :show-count="true"
                noChildrenText=""
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任人编号" prop="userId">
              <el-input v-model="form.userId" placeholder="请点击选择责任人" readonly @click.native="showUserSelectModal = true" style="cursor: pointer; width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="责任人姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="自动填充" readonly style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="责任人部门" prop="userDeptName">
              <!-- 存储部门ID但显示部门名称 -->
              <el-input v-model="form.userDeptName" placeholder="自动填充" readonly style="width: 100%;" />
              <!-- 隐藏的input用于存储部门ID -->
              <input type="hidden" v-model="form.userDeptId" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="form.contact" placeholder="自动填充" readonly style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资产部门与责任人部门是否一致" prop="isUserDeptDiff">
              <el-input 
                v-model="form.isUserDeptDiff === '1' ? '是' : '否'" 
                placeholder="自动判断" 
                readonly 
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="操作系统安装日期" prop="osInstallDate">
              <el-date-picker clearable
                v-model="form.osInstallDate"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择操作系统安装日期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作系统类型" prop="osId">
              <el-select v-model="form.osId" placeholder="请选择操作系统类型" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.os_type || []"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 占位列 -->
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备序列号" prop="deviceSerial">
              <el-input v-model="form.deviceSerial" placeholder="请输入设备序列号" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="CPU核心数" prop="numberOfCpu">
              <el-input v-model="form.numberOfCpu" placeholder="请输入CPU核心数" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内存容量" prop="memoryCapacity">
              <el-input v-model="form.memoryCapacity" placeholder="请输入内存容量（GB）" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="设备序列号" prop="deviceSn">
              <el-input v-model="form.deviceSn" placeholder="请输入设备序列号" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="启用日期" prop="activationDate">
              <el-date-picker clearable
                v-model="form.activationDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择启用日期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电子钥匙编号" prop="keyCode">
              <el-input v-model="form.keyCode" placeholder="请输入电子钥匙编号" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="使用情况" prop="usageId">
              <el-select v-model="form.usageId" placeholder="请选择使用情况" style="width: 100%;">
                <el-option
                  v-for="dict in dict.type.usage_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!-- 占位列 -->
          </el-col>
          <el-col :span="8">
            <!-- 占位列 -->
          </el-col>
        </el-row>
        

        

        


        <el-row>
          <el-col :span="8">
            <el-form-item label="安装涉密电子文件全生命标签和水印管理系统" prop="watermarkInstall">
              <el-radio-group v-model="form.watermarkInstall">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水印编码" prop="watermarkCode">
              <el-input v-model="form.watermarkCode" placeholder="请输入水印编码" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="安装计算机及其涉密载体保密管理系统" prop="electronicKeyInstall">
              <el-radio-group v-model="form.electronicKeyInstall">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="多网卡使用" prop="mulitNetworkCardsUse">
              <el-radio-group v-model="form.mulitNetworkCardsUse">
                <el-radio v-for="dict in dict.type.ban_or_admit" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="无线网卡使用" prop="wlanCardUse">
              <el-radio-group v-model="form.wlanCardUse">
                <el-radio v-for="dict in dict.type.none_or_adit_or_ban" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="串口使用" prop="serialPortUse">
              <el-radio-group v-model="form.serialPortUse">
                <el-radio v-for="dict in dict.type.none_or_adit_or_ban" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="红外蓝牙使用" prop="infraredBluetoothUse">
              <el-radio-group v-model="form.infraredBluetoothUse">
                <el-radio v-for="dict in dict.type.none_or_adit_or_ban" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网络共享访问" prop="networkSharedAccessUse">
              <el-radio-group v-model="form.networkSharedAccessUse">
                <el-radio v-for="dict in dict.type.ban_or_admit" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="并口使用" prop="parallelPortUse">
              <el-radio-group v-model="form.parallelPortUse">
                <el-radio v-for="dict in dict.type.none_or_adit_or_ban" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="记录本地文件操作" prop="fileRecordOperate">
              <el-radio-group v-model="form.fileRecordOperate">
                <el-radio v-for="dict in dict.type.use_or_not" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网络打印" prop="printerUse">
              <el-radio-group v-model="form.printerUse">
                <el-radio v-for="dict in dict.type.use_or_not" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本地打印" prop="localPrintInstall">
              <el-radio-group v-model="form.localPrintInstall">
                <el-radio v-for="dict in dict.type.ban_or_admit" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="移动存储设备" prop="removableStorage">
              <el-radio-group v-model="form.removableStorage">
                <el-radio v-for="dict in dict.type.admit_or_ban_or_reg" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="移动存储设备读写模式" prop="removableStorageRwMode">
              <el-radio-group v-model="form.removableStorageRwMode">
                <el-radio v-for="dict in dict.type.r_w" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相机录音笔" prop="cameraRecorder">
              <el-radio-group v-model="form.cameraRecorder">
                <el-radio v-for="dict in dict.type.admit_or_ban_or_reg" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="光驱" prop="cdRom">
              <el-radio-group v-model="form.cdRom">
                <el-radio v-for="dict in dict.type.admit_or_ban_or_readonly" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="软驱" prop="floppyDrive">
              <el-radio-group v-model="form.floppyDrive">
                <el-radio v-for="dict in dict.type.admit_or_ban_or_innersys" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="PCMCIA卡使用" prop="pcmciaUse">
              <el-radio-group v-model="form.pcmciaUse">
                <el-radio v-for="dict in dict.type.ban_or_admit" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否有其他" prop="isAnythingElse">
              <el-switch v-model="form.isAnythingElse" active-value="1" inactive-value="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.isAnythingElse === '1'">
            <el-form-item label="其他信息" prop="otherInfo">
              <el-input v-model="form.otherInfo" placeholder="请输入其他信息" type="textarea" style="width: 100%; height: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="对拷线使用" prop="duplicateLineUse">
              <el-radio-group v-model="form.duplicateLineUse">
                <el-radio v-for="dict in dict.type.ban_or_admit" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 硬盘信息表格 -->
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-form-item label="硬盘信息" style="margin-bottom: 10px;">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="addHddInfo">添加硬盘</el-button>
            </el-form-item>
            <el-table :data="form.hddInfoList || []" style="width: 100%">
              <el-table-column prop="hddType" label="硬盘类型" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.hddType" placeholder="请选择硬盘类型" size="small" style="width: 100%">
                    <el-option
                      v-for="dict in dict.type.hdd_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="hddSerial" label="硬盘序列号" width="300">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.hddSerial" placeholder="请输入硬盘序列号" size="small"/>
                </template>
              </el-table-column>
              <el-table-column prop="hddCapacity" label="硬盘容量（TB）" width="200">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.hddCapacity" placeholder="请输入硬盘容量" size="small" type="number" step="0.01"/>
                </template>
              </el-table-column>
              <el-table-column prop="hddStatus" label="硬盘状态" width="200">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.hddStatus" placeholder="请选择硬盘状态" size="small" style="width: 100%">
                    <el-option
                      v-for="dict in dict.type.usage_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入备注" size="small" type="textarea" :rows="1"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-delete" size="small" @click="removeHddInfo(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="(form.hddInfoList || []).length === 0" class="no-data-text">暂无硬盘信息，点击"添加硬盘"按钮添加</div>
          </el-col>
        </el-row>
        
        <!-- 网卡信息表格 -->
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-form-item label="网卡信息" style="margin-bottom: 10px;">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="addNetworkCardInfo">添加网卡</el-button>
            </el-form-item>
            <el-table :data="form.networkCardInfoList || []" style="width: 100%">
              <el-table-column prop="ipAddress" label="IP地址" width="400">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.ipAddress" placeholder="请输入IP地址" size="small"/>
                </template>
              </el-table-column>
              <el-table-column prop="macAddress" label="MAC地址" width="400">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.macAddress" placeholder="请输入MAC地址" size="small"/>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.remark" placeholder="请输入备注" size="small" type="textarea" :rows="1"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-delete" size="small" @click="removeNetworkCardInfo(scope.$index)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-if="(form.networkCardInfoList || []).length === 0" class="no-data-text">暂无网卡信息，点击"添加网卡"按钮添加</div>
          </el-col>
        </el-row>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 用户选择弹窗 -->
    <el-dialog title="选择责任人" :visible.sync="showUserSelectModal" width="70%" append-to-body>
      <div style="margin-bottom: 15px;">
        <el-input v-model="userSearchName" placeholder="请输入责任人编号" style="width: 200px; margin-right: 10px;"></el-input>
        <el-button type="primary" @click="searchUserByName">搜索</el-button>
        <el-button @click="resetUserSearch">重置</el-button>
      </div>
      <el-table ref="userTable" v-loading="userLoading" :data="filteredUserList" @row-click="handleUserRowClick" @selection-change="handleUserSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userName" label="用户编号" width="100" />
        <el-table-column prop="nickName" label="用户姓名" width="120" />
        <el-table-column prop="deptName" label="所属部门" width="180" />
        <el-table-column prop="phonenumber" label="联系方式" width="150" />
        <el-table-column prop="email" label="邮箱" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showUserSelectModal = false">取消</el-button>
        <el-button type="primary" @click="confirmUserSelect">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceManage, getDeviceManage, delDeviceManage, addDeviceManage, updateDeviceManage, saveDeviceHddInfo, getDeviceHddInfo, getDeviceNetworkCardInfo, saveDeviceNetworkCardInfo } from "@/api/manage/deviceManage";
import { userTreeselect, listUser } from "@/api/system/user";
import { treeDictTree } from "@/api/test/tree_dict";
import { treeselect } from "@/api/system/dept";
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import { selectDictLabel } from '@/utils/ruoyi';

export default {
    name: "DeviceManage",
    dicts: ['secret_level', 'network_type', 'device_brand', 'usage_status', 'device_source', 'os_type', 'sys_yes_no', 'ban_or_admit', 'none_or_adit_or_ban', 'use_or_not', 'admit_or_ban_or_readonly', 'r_w', 'admit_or_ban_or_reg', 'admit_or_ban_or_innersys', 'device_purpose', 'hdd_type'],
    
    
    data() {
      return {
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示高级搜索条件
        showAdvancedSearch: false,
        // 总条数
        total: 0,
        // 设备管理表格数据
        deviceManageList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示用户选择弹窗
        showUserSelectModal: false,
        // 使用情况时间范围
        daterangeOsInstallDate: [],
        // 使用情况时间范围
        daterangeActivationDate: [],
        // 用户搜索关键词
        userSearchName: '',
        // 过滤后的用户列表
        filteredUserList: [],
        // 高级搜索按钮文本
        advancedSearchText: '展开搜索',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceCode: null,
          brandId: null,
          model: null,
          sourceId: '',
          securityId: '',
          networkId: '',
          contact: null,
          osInstallDate: null,
          osId: '',
          deviceSerial: null,
          numberOfCpu: null,
          memoryCapacity: null,
          watermarkCode: null,
          activationDate: null,
          keyCode: null,
          usageId: '',
          typeId: '',
          dictName: '',
          purposeId: null,
          deptId: '',
          deptName: '',
          userId: '',
          userName: '',
          hddSerial: null,
          ipAddress: null,
          macAddress: null
        },
        // 表单参数
        form: {
          watermarkInstall: "0",
          electronicKeyInstall: "0",
          mulitNetworkCardsUse: "0",
          wlanCardUse: "0",
          serialPortUse: "0",
          parallelPortUse: "0",
          infraredBluetoothUse: "0",
          networkSharedAccessUse: "0",
          fileRecordOperate: "0",
          printerUse: "0",
          localPrintInstall: "0",
          removableStorage: "0",
          removableStorageRwMode: "0",
          cameraRecorder: "0",
          cdRom: "0",
          floppyDrive: "0",
          pcmciaUse: "0",
          duplicateLineUse: "0",
          isAnythingElse: "0",
          otherInfo: '',
          osId: '',
          osInstallDate: '',
          hddInfoList: [],
          networkCardInfoList: []
        },
        // 表单校验
        rules: {},
        // 树形字典数据
        treeDictData: [],
        // 用户列表加载状态
        userLoading: false,
        // 用户列表数据
        userList: [],
        // 当前选中的用户
        selectedUser: null,
        // 设备类型树形数据
        deviceTypeData: [],
        // 设备用途树形数据
        devicePurposeData: [],
        // 部门树形数据
        deptTreeData: [],
        // 用户树形数据
        userTreeData: []
      };
    },
    // 监听表单数据变化
    watch: {
      'form.deptId': function() {
        this.checkDeptConsistency();
      },
      'form.userId': function() {
        this.checkDeptConsistency();
      },
      'showUserSelectModal': function(newVal) {
        if (newVal) {
          this.loadUserList();
        }
      }
    },
    created() {
      this.getList();
      this.getTreeDictData();
      this.getDeviceTypeData();
      this.getDevicePurposeData();
      this.getDeptTreeData();
      this.getUserTreeData();
      // 手动获取操作系统类型字典数据
      this.getDicts('os_type').then(() => {
        // 字典数据已加载，可以在这里执行需要字典数据的操作
        console.log('OS Type dict data loaded:', this.dict.type.os_type);
      }).catch(error => {
        console.error('Failed to load OS Type dict data:', error);
      });
      
      // 手动获取硬盘类型字典数据
      this.getDicts('hdd_type').then(() => {
        // 字典数据已加载，可以在这里执行需要字典数据的操作
        console.log('HDD Type dict data loaded:', this.dict.type.hdd_type);
      }).catch(error => {
        console.error('Failed to load HDD Type dict data:', error);
      });
      
      // 手动获取使用状态字典数据
      this.getDicts('usage_status').then(() => {
        // 字典数据已加载，可以在这里执行需要字典数据的操作
        console.log('Usage Status dict data loaded:', this.dict.type.usage_status);
      }).catch(error => {
        console.error('Failed to load Usage Status dict data:', error);
      });
    },
    methods: {
        /** 根据字典类型和值获取对应的标签 */
        getDictLabel(dictType, dictValue) {
            return selectDictLabel(this.dict.type[dictType], dictValue);
        },
        
        /** 切换高级搜索显示状态 */
        toggleAdvancedSearch() {
            this.showAdvancedSearch = !this.showAdvancedSearch;
            this.advancedSearchText = this.showAdvancedSearch ? '隐藏搜索' : '高级搜索';
        },
        
        /** 获取树形字典数据 */
        getTreeDictData() {
            treeDictTree().then(response => {
                // 直接使用API返回的数据，通过el-cascader的props属性进行字段映射
                // 处理空的children数组
                this.treeDictData = this.filterEmptyChildren(response.data);
            });
        },
        
        /** 获取设备类型树形数据 */
        getDeviceTypeData() {
            // 筛选值开头为"01"的数据
            const query = {
                dictValueStartWith: '01'
            };
            treeDictTree(query).then(response => {
                // 处理空的children数组
                this.deviceTypeData = this.filterEmptyChildren(response.data);
            });
        },
        
        /** 获取设备用途树形数据 */
        getDevicePurposeData() {
            // 筛选值开头为"03"的数据
            const query = {
                dictValueStartWith: '03'
            };
            treeDictTree(query).then(response => {
                // 处理空的children数组
                this.devicePurposeData = this.filterEmptyChildren(response.data);
            });
        },
        
        /** 过滤掉空的children数组 */
        filterEmptyChildren(nodes) {
            if (!Array.isArray(nodes)) {
                return nodes;
            }
            
            return nodes.map(node => {
                const newNode = { ...node };
                // 如果有children且children不为空数组，递归处理
                if (newNode.children && Array.isArray(newNode.children) && newNode.children.length > 0) {
                    newNode.children = this.filterEmptyChildren(newNode.children);
                } else {
                    // 如果没有children或children为空数组，删除children属性
                    delete newNode.children;
                }
                return newNode;
            });
        },
        
        /** 获取部门树形数据 */
        getDeptTreeData() {
            treeselect().then(response => {
                // 直接使用全部部门数据，不进行筛选
                this.deptTreeData = response.data;
            });
        },
        
        /** 获取用户树形数据 */
        getUserTreeData() {
            // 调用用户树选择器接口获取用户树形数据
            userTreeselect().then(response => {
                // 需要先获取用户列表来匹配userId、userName和用户部门信息
                listUser().then(userResponse => {
                    const userMap = new Map();
                    const userDeptMap = new Map(); // 存储用户ID到用户部门ID的映射
                    userResponse.rows.forEach(user => {
                        userMap.set(String(user.userId), user.userName);
                        userDeptMap.set(String(user.userId), user.deptId);
                    });
                    
                    // 转换数据结构，确保id和label都使用user_name
                    this.userTreeData = response.data.map(node => {
                        const userIdStr = String(node.id);
                        const userName = userMap.get(userIdStr);
                        // 确保id和label始终是user_name，即使找不到对应关系也不使用nick_name
                        return {
                            id: userName || '',  // 使用用户账号作为ID
                            label: userName || '',  // 使用用户账号作为显示文本
                            deptId: userDeptMap.get(userIdStr) || null // 存储用户对应的部门ID
                        };
                    }).filter(node => node.id !== ''); // 过滤掉无效的用户
                });
            });
        },
        
        /** 加载用户列表 */
        loadUserList() {
            this.userLoading = true;
            listUser({ pageNum: 1, pageSize: 100 }).then(response => {
                // 为每个用户添加部门名称
                this.userList = response.rows.map(user => {
                    // 使用getDeptNameById方法通过部门ID获取部门名称
                    user.deptName = this.getDeptNameById(user.deptId);
                    return user;
                });
                // 初始化过滤后的用户列表
                this.filteredUserList = [...this.userList];
                this.userLoading = false;
            }).catch(() => {
                this.userLoading = false;
            });
        },
        
        /** 根据责任人编号搜索用户 */
        searchUserByName() {
            if (!this.userSearchName.trim()) {
                this.filteredUserList = [...this.userList];
                return;
            }
            
            const searchName = this.userSearchName.trim().toLowerCase();
            this.filteredUserList = this.userList.filter(user => 
                user.userName && user.userName.toLowerCase().includes(searchName)
            );
            
            // 如果只找到一个匹配的用户，自动选择该用户
            if (this.filteredUserList.length === 1) {
                this.selectedUser = this.filteredUserList[0];
                this.$nextTick(() => {
                    const table = this.$refs.userTable;
                    if (table) {
                        table.clearSelection();
                        table.toggleRowSelection(this.selectedUser, true);
                    }
                });
            }
        },
        
        /** 重置用户搜索 */
        resetUserSearch() {
            this.userSearchName = '';
            this.filteredUserList = [...this.userList];
            this.selectedUser = null;
            this.$nextTick(() => {
                const table = this.$refs.userTable;
                if (table) {
                    table.clearSelection();
                }
            });
        },
        
        /** 处理用户行点击 */
        handleUserRowClick(row) {
            this.selectedUser = row;
            // 清除之前的选择
            this.$nextTick(() => {
                const table = this.$refs.userTable;
                if (table) {
                    table.clearSelection();
                    table.toggleRowSelection(row, true);
                }
            });
        },
        
        /** 处理用户选择变化（复选框选择） */
        handleUserSelectionChange(selection) {
            if (selection && selection.length > 0) {
                this.selectedUser = selection[selection.length - 1]; // 选择最后一个选中的用户
            } else {
                this.selectedUser = null;
            }
        },
        
        /** 确认选择用户 */
        confirmUserSelect() {
            if (this.selectedUser) {
                this.handleUserSelect(this.selectedUser);
            } else {
                this.$modal.msgWarning("请选择用户");
            }
        },
        /** 自动判断资产部门与责任人部门是否一致 */
        checkDeptConsistency() {
            if (this.form.deptId && this.form.userId) {
                // 查找选中的用户对应的部门ID
                // 注意：this.form.userId 现在存储的是用户账号(userName)
                const findUserDeptId = (nodes, userAccount) => {
                    for (const node of nodes) {
                        if (node.id === userAccount) {
                            return node.deptId;
                        }
                        if (node.children && node.children.length > 0) {
                            const result = findUserDeptId(node.children, userAccount);
                            if (result) {
                                return result;
                            }
                        }
                    }
                    return null;
                };
                
                const userDeptId = findUserDeptId(this.userTreeData, this.form.userId);
                
                // 比较设备部门ID和用户部门ID
                if (userDeptId && String(this.form.deptId) === String(userDeptId)) {
                    this.form.isUserDeptDiff = "1"; // 1表示部门一致
                } else {
                    this.form.isUserDeptDiff = "2"; // 2表示部门不一致
                }
            } else {
                this.form.isUserDeptDiff = "";
            }
        },
        
        /** treeselect组件数据格式化函数 */
        normalizer(node) {
            return {
                id: node.id,
                label: node.label,
                children: node.children
            };
        },
        
        /** 根据部门ID获取部门名称 */
        getDeptNameById(deptId) {
            if (!deptId || !this.deptTreeData || this.deptTreeData.length === 0) {
                return '';
            }
            
            // 递归查找部门名称
            const findDeptName = (nodes, id) => {
                for (const node of nodes) {
                    // 处理可能的类型不匹配问题
                    if (String(node.id) === String(id)) {
                        return node.label;
                    }
                    if (node.children && node.children.length > 0) {
                        const result = findDeptName(node.children, id);
                        if (result) {
                            return result;
                        }
                    }
                }
                return '';
            };
            
            return findDeptName(this.deptTreeData, deptId);
        },
        
        /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOsInstallDate && '' != this.daterangeOsInstallDate) {
        this.queryParams.params["beginOsInstallDate"] = this.daterangeOsInstallDate[0];
        this.queryParams.params["endOsInstallDate"] = this.daterangeOsInstallDate[1];
      }
      if (null != this.daterangeActivationDate && '' != this.daterangeActivationDate) {
        this.queryParams.params["beginActivationDate"] = this.daterangeActivationDate[0];
        this.queryParams.params["endActivationDate"] = this.daterangeActivationDate[1];
      }
      listDeviceManage(this.queryParams).then(response => {
        this.deviceManageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        deviceCode: null,
        typeId: null,
        locationId: null,
        brandId: null,
        model: null,
        sourceId: null,
        securityId: null,
        purposeId: null,
        networkId: null,
        deptId: null,
        userId: null,
        userName: null,
        userDeptId: null,
        userDeptName: null,
        isUserDeptDiff: null,
        contact: null,
        osInstallDate: '',
        osId: '',
        deviceSerial: null,
        numberOfCpu: null,
        memoryCapacity: null,
        watermarkCode: null,
        activationDate: null,
        keyCode: null,
        usageId: null,
        watermarkInstall: "0",
        electronicKeyInstall: "0",
        mulitNetworkCardsUse: "0",
        wlanCardUse: "0",
        serialPortUse: "0",
        parallelPortUse: "0",
        infraredBluetoothUse: "0",
        networkSharedAccessUse: "0",
        fileRecordOperate: "0",
        printerUse: "0",
        localPrintInstall: "0",
        removableStorage: "0",
        removableStorageRwMode: "0",
        cameraRecorder: "0",
        cdRom: "0",
        floppyDrive: "0",
        pcmciaUse: "0",
        duplicateLineUse: "0",
        isAnythingElse: "0",
        otherInfo: '',
        hddInfoList: [],
        networkCardInfoList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 添加硬盘信息 */
        addHddInfo() {
          console.log('addHddInfo called');
          // 确保hddInfoList始终是一个数组
          if (!Array.isArray(this.form.hddInfoList)) {
            this.form.hddInfoList = [];
            console.log('Initialized hddInfoList as empty array');
          }
          // 使用Vue.set来确保响应式更新
          this.$set(this.form.hddInfoList, this.form.hddInfoList.length, {
            hddType: '',
            hddSerial: '',
            hddCapacity: '',
            hddStatus: '1', // 默认正常
            remark: ''
          });
          console.log('Added new HDD info, current length:', this.form.hddInfoList.length);
          // 强制更新视图
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        },
        
        /** 移除硬盘信息 */
        removeHddInfo(index) {
          this.form.hddInfoList.splice(index, 1);
        },
        
        /** 添加网卡信息 */
        addNetworkCardInfo() {
          console.log('addNetworkCardInfo called');
          // 确保networkCardInfoList始终是一个数组
          if (!Array.isArray(this.form.networkCardInfoList)) {
            this.form.networkCardInfoList = [];
            console.log('Initialized networkCardInfoList as empty array');
          }
          // 使用Vue.set来确保响应式更新
          this.$set(this.form.networkCardInfoList, this.form.networkCardInfoList.length, {
            ipAddress: '',
            macAddress: '',
            remark: ''
          });
          console.log('Added new network card info, current length:', this.form.networkCardInfoList.length);
          // 强制更新视图
          this.$nextTick(() => {
            this.$forceUpdate();
          });
        },
        
        /** 移除网卡信息 */
        removeNetworkCardInfo(index) {
          this.form.networkCardInfoList.splice(index, 1);
        },
        
        /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOsInstallDate = [];
      this.daterangeActivationDate = [];
      this.resetForm("queryForm");
      // 确保dictName字段被正确重置
      this.queryParams.dictName = '';
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
        handleAdd() {
          this.reset();
          this.open = true;
          this.title = "添加设备管理";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset();
          // 确保正确获取deviceId
          const deviceId = row && row.deviceId ? row.deviceId : this.ids[0];
          if (!deviceId) {
            this.$modal.msgError('请选择要修改的设备');
            return;
          }
          
          getDeviceManage(deviceId).then(response => {
            // 确保form是一个对象
            this.form = response.data || {};
            console.log('Device data loaded:', this.form);
            
            // 确保部门名称正确显示（如果只有部门ID）
            if (this.form.userDeptId && !this.form.userDeptName) {
              this.form.userDeptName = this.getDeptNameById(this.form.userDeptId);
            }
            // 自动判断资产部门与责任人部门是否一致
            this.checkDeptConsistency();
            
            // 确保hddInfoList和networkCardInfoList是数组
            if (!Array.isArray(this.form.hddInfoList)) {
              this.form.hddInfoList = [];
            }
            if (!Array.isArray(this.form.networkCardInfoList)) {
              this.form.networkCardInfoList = [];
            }
            
            // 获取设备的硬盘和网卡信息
            if (this.form.deviceCode) {
              // 使用Promise.all确保两个请求都完成后再更新视图
              Promise.all([
                getDeviceHddInfo(this.form.deviceCode).then(hddResponse => {
                  console.log('HDD info loaded:', hddResponse.data);
                  // 使用Vue.set确保响应式更新
                  this.$set(this.form, 'hddInfoList', hddResponse.data || []);
                }).catch(error => {
                  console.error('Failed to load HDD info:', error);
                  this.$set(this.form, 'hddInfoList', []);
                }),
                getDeviceNetworkCardInfo(this.form.deviceCode).then(networkCardResponse => {
                  console.log('Network card info loaded:', networkCardResponse.data);
                  // 使用Vue.set确保响应式更新
                  this.$set(this.form, 'networkCardInfoList', networkCardResponse.data || []);
                }).catch(error => {
                  console.error('Failed to load network card info:', error);
                  this.$set(this.form, 'networkCardInfoList', []);
                })
              ]).then(() => {
                this.open = true;
                this.title = "修改设备管理";
                
                // 强制更新视图
                this.$nextTick(() => {
                  this.$forceUpdate();
                  console.log('View updated after loading data');
                });
              });
            } else {
              console.log('No deviceCode, setting empty lists');
              this.$set(this.form, 'hddInfoList', []);
              this.$set(this.form, 'networkCardInfoList', []);
              
              this.open = true;
              this.title = "修改设备管理";
              
              // 强制更新视图
              this.$nextTick(() => {
                this.$forceUpdate();
              });
            }
          }).catch(error => {
            console.error('获取设备详情失败:', error);
            this.$modal.msgError('获取设备详情失败，请重试');
          });
        },
    
    /** 选择用户后处理 */
    handleUserSelect(user) {
      // 确保使用正确的字段名设置表单数据
      this.form.userId = user.userName;  // 保留用户ID用于后端处理
      this.form.userName = user.nickName;  // 设置用户姓名
      this.form.userDeptId = user.deptId;  // 存储部门ID
      this.form.userDeptName = user.deptName;  // 显示部门名称
      this.form.contact = user.phonenumber;  // 设置联系方式
      this.showUserSelectModal = false;
      this.checkDeptConsistency();
      
      // 强制更新视图
      this.$forceUpdate();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            // 修改设备
            updateDeviceManage(this.form).then(response => {
              // 保存网卡信息的函数
              const saveNetworkCardInfo = () => {
                if (this.form.networkCardInfoList && this.form.networkCardInfoList.length > 0) {
                  // 为每条网卡信息设置device_code
                  const networkCardInfoWithDeviceCode = this.form.networkCardInfoList.map(card => ({
                    ...card,
                    deviceCode: this.form.deviceCode
                  }));
                  
                  // 调用保存网卡信息的API
                  saveDeviceNetworkCardInfo({
                    deviceCode: this.form.deviceCode,
                    networkCardInfoList: networkCardInfoWithDeviceCode
                  }).catch(() => {
                    this.$modal.msgWarning("更新失败");
                  });
                }
              };
              
              // 如果有硬盘信息，保存硬盘信息
              if (this.form.hddInfoList && this.form.hddInfoList.length > 0) {
                // 为每条硬盘信息设置device_code
                const hddInfoWithDeviceCode = this.form.hddInfoList.map(hdd => ({
                  ...hdd,
                  deviceCode: this.form.deviceCode
                }));
                
                // 调用保存硬盘信息的API
                saveDeviceHddInfo({
                  deviceCode: this.form.deviceCode,
                  hddInfoList: hddInfoWithDeviceCode
                }).then(() => {
                  this.$modal.msgSuccess("更新成功");
                  saveNetworkCardInfo(); // 保存网卡信息
                  this.open = false;
                  this.getList();
                }).catch(() => {
                  this.$modal.msgWarning("更新失败");
                  saveNetworkCardInfo(); // 保存网卡信息
                  this.open = false;
                  this.getList();
                });
              } else {
                this.$modal.msgSuccess("修改成功");
                saveNetworkCardInfo(); // 保存网卡信息
                this.open = false;
                this.getList();
              }
            });
          } else {
            // 新增设备
            addDeviceManage(this.form).then(response => {
              // 获取后端返回的包含设备编码的完整设备信息
              const savedDeviceInfo = response.data;
              // 获取正确的设备编码
              const deviceCode = savedDeviceInfo.deviceCode;
              
              // 保存网卡信息的函数
              const saveNetworkCardInfo = () => {
                if (this.form.networkCardInfoList && this.form.networkCardInfoList.length > 0) {
                  // 为每条网卡信息设置正确的device_code
                  const networkCardInfoWithDeviceCode = this.form.networkCardInfoList.map(card => ({
                    ...card,
                    deviceCode: deviceCode
                  }));
                   
                  // 调用保存网卡信息的API
                  saveDeviceNetworkCardInfo({
                    deviceCode: deviceCode,
                    networkCardInfoList: networkCardInfoWithDeviceCode
                  }).catch(() => {
                    this.$modal.msgWarning("网卡信息保存失败");
                  });
                }
              };
               
              // 如果有硬盘信息，保存硬盘信息
              if (this.form.hddInfoList && this.form.hddInfoList.length > 0) {
                // 为每条硬盘信息设置正确的device_code
                const hddInfoWithDeviceCode = this.form.hddInfoList.map(hdd => ({
                  ...hdd,
                  deviceCode: deviceCode
                }));
                 
                // 调用保存硬盘信息的API
                  saveDeviceHddInfo({
                    deviceCode: deviceCode,
                    hddInfoList: hddInfoWithDeviceCode
                  }).then(() => {
                    this.$modal.msgSuccess("新增成功");
                    saveNetworkCardInfo(); // 保存网卡信息
                    this.open = false;
                    this.getList();
                  }).catch(() => {
                    this.$modal.msgWarning("新增失败");
                    saveNetworkCardInfo(); // 保存网卡信息
                    this.open = false;
                    this.getList();
                  });
              } else {
                this.$modal.msgSuccess("新增成功");
                saveNetworkCardInfo(); // 保存网卡信息
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('是否确认删除设备管理编号为"' + deviceIds + '"的数据项？').then(function() {
        return delDeviceManage(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 详情按钮操作 */
    handleNewDetail(row) {
      const deviceId = row.deviceId;
      // 获取品牌、密级、来源的中文名称
      const brandName = this.getDictLabel('device_brand', row.brandId);
      const securityName = this.getDictLabel('secret_level', row.securityId);
      const sourceName = this.getDictLabel('device_source', row.sourceId);
      
      this.$router.push({
        path: '/manage/deviceManage/detail/' + deviceId,
        query: {
          brandName: brandName,
          securityName: securityName,
          sourceName: sourceName
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/deviceManage/export', {
        ...this.queryParams
      }, `deviceManage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
